<template>
	<el-form :model="data" :inline="data.inline" :label-width="data.labelWidth" ref="ruleFormRef">
		<slot></slot>
		<!-- 提交按钮 -->
		<slot name="btn">
			<el-form-item v-if="showBtn">
				<el-button type="primary" @click="submitForm">搜索</el-button>
				<el-button @click="resetForm">重置</el-button>
			</el-form-item>
		</slot>
	</el-form>
</template>

<script setup lang="ts">
	/**
	 * @property { Object } data 表单数据
	 * @event {Function()} submit 提交 
	 * @event {Function()} reset 重置触发
	 */
	import { ref } from 'vue';
	import type { FormInstance } from 'element-plus';
	// 接收父组件传递的 formData
	const props = defineProps({
		data: {
			default: () => ({}),
			type: Object,
			required: true,
		},
		showBtn:{
			default:true,
			type:Boolean
		}
	});
	const ruleFormRef = ref<FormInstance>()
	const emit = defineEmits(['submit', 'reset']);
	const submitForm = () => {
		// 提交表单时，提取 fields 中的值
		let searchCriteria = {}
		if(props.data.isforEach){
			Object.keys(props.data).forEach((key)=>{
				if(props.data[key].fields){
					const dataValue = props.data[key].fields.reduce((acc : any, field : any) => {
						acc[field.name] = field.value;
						return acc;
					}, {});
					Object.assign(searchCriteria,dataValue)
				}
			})
		}else{
			searchCriteria = props.data.fields.reduce((acc : any, field : any) => {
				acc[field.name] = field.value;
				return acc;
			}, {});
		}
		emit('submit',searchCriteria)
	};
	const submit = () => {
		// 提交表单时，提取 fields 中的值
		let searchCriteria = {}
		if(props.data.isforEach){
			Object.keys(props.data).forEach((key)=>{
				if(props.data[key].fields){
					const dataValue = props.data[key].fields.reduce((acc : any, field : any) => {
						acc[field.name] = field.value;
						return acc;
					}, {});
					Object.assign(searchCriteria,dataValue)
				}
			})
		}else{
			searchCriteria = props.data.fields.reduce((acc : any, field : any) => {
				acc[field.name] = field.value;
				return acc;
			}, {});
		}
		return searchCriteria
	}
	const resetForm = () => {
		// 重置表单
		if(props.data.isforEach){
			Object.keys(props.data).forEach((key)=>{
				if(key != 'isforEach' && key != 'labelWidth'){
					props.data[key].fields.forEach((field : any) => {
						field.value = '';
					});
				}
			})
		}else{
			props.data.fields.forEach((field : any) => {
				field.value = '';
			});
		}
		ruleFormRef.value?.resetFields();
		submitForm()
	};
	defineExpose({
		submit,
		resetForm
	})
</script>